package mfuny.ggongal.admin.ad;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.games.GameDao;
import mfuny.ggongal.admin.gift.GiftCardDao;
import mfuny.ggongal.admin.gift.GiftDao;
import mfuny.ggongal.admin.http.HttpAd;
import mfuny.ggongal.admin.timetable.TimeDao;

import org.json.simple.JSONObject;
import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class AdSpecialService {
	SqlMapClient sqlMapper;
	
	ModelAndView mav;
	
	AdDao resultClass;
	List<AdDao> resultList;
	List<GameDao> gameList;
	List<GiftDao> giftList;
	List<HashMap<String, Object>> mapList;
	HashMap<String, String> map;
	GameDao gameClass;
	TimeDao timedClass;
	
	String selectedTime;
	
	public AdSpecialService() throws Exception {
		sqlMapper = Server.getSqlMapper( );
		
		mav = new ModelAndView();
		resultClass = new AdDao();
		resultList = new ArrayList<AdDao>();
		gameList = new ArrayList<GameDao>();
		giftList = new ArrayList<GiftDao>();
		mapList = new ArrayList<HashMap<String, Object>>();
		map = new HashMap<String, String>();
		gameClass = new GameDao();
		timedClass = new TimeDao();
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView specialGame() throws Exception {
//		resultList = sqlMapper.queryForList( "ad_selectSpecialAll", null );
		mapList = sqlMapper.queryForList( "ad_selectForMapByService", "special" );
		mav.clear( );
		mav.setViewName( "/ad/special/specialGame.ga" );
		mav.addObject( "mapList", mapList );
		mav.addObject( "listSize", mapList.size( ) );
		return mav;
	}
	
	public ModelAndView regSpecialGame0() throws Exception {
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGame0.ga" );
		return mav;
	}
	
	public ModelAndView regSpecialGame1() throws Exception {
		map.clear( );
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGame1.ga" );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView regSpecialGame2() throws Exception {
		gameList = sqlMapper.queryForList( "games_selectAll", null );
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGame2.ga" );
		mav.addObject( "gameList", gameList );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView regSpecialGame3( AdDao paramClass ) throws Exception {
		gameClass = (GameDao) sqlMapper.queryForObject( "games_selectNo", paramClass.getGame_no( ) );
		giftList = sqlMapper.queryForList( "gift_selectForContents", paramClass.getContents_no( ) );
		List<GiftCardDao> giftCardList = sqlMapper.queryForList("card_selectAll", null);
		
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGame3.ga" );
		mav.addObject( "gameClass", gameClass );
		mav.addObject( "giftList", giftList );
		mav.addObject("giftCardList", giftCardList);
		return mav;
	}
	
	public ModelAndView regSpecialGame4() throws Exception {
		map.clear( );
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGame4.ga" );
		return mav;
	}
	
	public ModelAndView specialSelection( String days ) throws Exception {
		timedClass = (TimeDao) sqlMapper.queryForObject( "time_selectOne", days );
		mav.clear( );
		mav.setViewName( "/ad/special/specialSelection" );
		if ( map.containsKey( days )) {
			selectedTime = map.get( days );
			mav.addObject( "selectedTime", selectedTime );
		}
		mav.addObject( "timedClass", timedClass );
		return mav;
	}
	
	public ModelAndView selectedSpec( String days, String time ) throws Exception {
		if ( time == "" ) {
			map.remove( days );
		} else {
			map.put( days, time );
		}
		mav.clear( );
		mav.setViewName( "/ad/time/blank" );
		return mav;
	}
	
	public ModelAndView regSpecialGameCheck( HttpSession session ) throws Exception {
		resultClass = (AdDao) session.getAttribute( "specialGame" );
		resultClass.setService( "special" );
		resultClass.setDays( getDaysFinal() );
		session.setAttribute( "specialGame", resultClass );
		mav.clear( );
		mav.setViewName( "/ad/special/regSpecialGameCheck.ga" );
		mav.addObject( "resultClass", resultClass );
		return mav;
	}
	
	public String getDaysFinal() {
		String finalDays = "";
		Iterator<Entry<String, String>> iter = map.entrySet( ).iterator( );
		Entry<String, String> en;
		while( iter.hasNext( ) ) {
			en = iter.next( );
			finalDays += ( finalDays.equals( "" ) ? "" : "," ) + en.getKey( ) + "/" + en.getValue( );
		}
		return finalDays;
	}
	
	public void regSpecialGameFinal( HttpSession session ) throws Exception {
		resultClass = (AdDao) session.getAttribute( "specialGame" );
		resultClass.setRegdate( new Timestamp( System.currentTimeMillis( )) );
		try {
			sqlMapper.startTransaction( );
			sqlMapper.update( "ad_insert", resultClass );
			int ad_no = (Integer) sqlMapper.queryForObject( "ad_selectLastNo", null );
			Iterator<Entry<String, String>> iter = map.entrySet( ).iterator( );
			Entry<String, String> en;
			int isDays = 0;
			sqlMapper.startBatch( );
			while( iter.hasNext( ) ) {
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				en = iter.next( );
				paramMap.put( "days", en.getKey( ) );
				paramMap.put( "time", "h" + en.getValue( ) );
				paramMap.put( "ad_no", ad_no );
				isDays = (Integer) sqlMapper.queryForObject( "time_isDays", en.getKey( ) );
				if ( isDays > 0 ) {
					sqlMapper.update( "time_updateSpecialGame", paramMap );
				} else {
					sqlMapper.update( "time_insertSpecialGame", paramMap );
				}
			}
			sqlMapper.executeBatch( );
			sqlMapper.commitTransaction( );
			session.removeAttribute( "specialGame" );
			map.clear( );
		} finally {
			sqlMapper.endTransaction( );
		}
	}
	
	//광고 상세보기.
	@SuppressWarnings("unchecked")
	public ModelAndView detailSpecialGame(int ad_no) throws Exception {
		JSONObject giftClass = new HttpAd().ad_getGiftDetailWithRank(ad_no);
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("ad_selectAllOne2", ad_no);
		int score = MissionDetail.getScore_mission((String)resultClass.get("mission"));
		mav.clear();
		mav.setViewName("/ad/special/detailSpecialGame.ga");
		mav.addObject("resultClass", resultClass);
		mav.addObject("giftClass", giftClass);
		mav.addObject("m_score", score);
		return mav;
	}
	
	//스페셜게임 삭제하기(컨트롤).
	public ModelAndView deleteSGame(int ad_no) throws Exception {
		int result = deleteSGameWork(ad_no);
		mav.clear();
		mav.setViewName("/blank");
		mav.addObject("value", result);
		return mav;
	}
	
	//스페셜게임 삭제하기(처리).
	@SuppressWarnings("unchecked")
	public int deleteSGameWork(int ad_no) throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", ad_no);
		String[] beforeDays = ad.getDays().split(",");
		int result = 0;
		
		List<String> days = new ArrayList<String>();
		try {
			sqlMapper.startTransaction();
			for(int i = 0; i < beforeDays.length; i++) {
				days.add( beforeDays[i].split("/")[0] );
			}
			List<TimeDao> timeList = sqlMapper.queryForList("time_selectMulti", days);			//쿼리문.	광고 시행날짜의 타임테이블 리스트 가져오기.
			
			for(int i = 0; i < timeList.size(); i++) {
				TimeDao time = timeList.get(i);
				Method[] m = time.getClass().getMethods();
				for(int j = 0; j < m.length; j++) {
					if( m[j].getName().indexOf("getH") > -1 ) {
						Object valueObj = m[j].invoke(time);
						String value = null;
						if( valueObj == null ) {
							continue;
						}
						value = (String)valueObj;
						if( value.equals(String.valueOf(ad_no))) {
							value = null;
							Method m2 = time.getClass().getMethod( m[j].getName().replace("get", "set"), new String().getClass() );
							m2.invoke(time, value );
						}
					}
				}
				result = sqlMapper.update("time_updateForModify", time);					//쿼리문. 타임테이블에 특정 광고번호만 지우고 업데이트.
				if( result <= 0 ) {
					throw new Exception("timetable update error");
				}
			}
			
			result = sqlMapper.update("ad_delete", ad_no);										//쿼리문. 광고 지우기.
			if( result <= 0 ) {
				throw new Exception("delete ad error");
			}
			sqlMapper.commitTransaction();
			result = 1;
			
		}catch(Exception e) {
			Debug.toDebugFile(e, "deleteSGame");
			result = -1;
			
		}finally {
			sqlMapper.endTransaction();
		}
		
		return result;
	}
}
